package com.android.picotts.ui.widget;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.PixelFormat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.picotts.MyApplication;
import com.android.picotts.R;
import com.android.picotts.businiss.SpriterManager;
import com.android.picotts.businiss.model.Spriter;
import com.android.picotts.businiss.model.SpriterType;
import com.android.picotts.ui.activity.MainActivity;

public class FloatView extends LinearLayout implements LinearLayout.OnClickListener, LinearLayout.OnTouchListener{

    //创建浮动窗口设置布局参数的对象
    private static WindowManager mWindowManager;
    private static WindowManager.LayoutParams wmParams;
    //定义浮动窗口布局
    private static LayoutInflater inflater;
    
    private ImageView mFloatView;
    
    private LinearLayout spriteLay;
    private FlowLayout flowView;
    private TextView add_curapp,back, del, add;
    
    private DisplayMetrics dm;
    private boolean isMoving = false;
    private boolean isOpenFloat = false;
    private boolean isEditable = false;
    private boolean isHide = false;
    
    public FloatView(Context context) {
        this(context, null);
    }
    
    public FloatView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();        
        //浮动窗口按钮  
        mFloatView = (ImageView)findViewById(R.id.tx_float);
        //设置监听浮动窗口的触摸移动 
        setOnTouchListener(this);
        //容器初始化
        spriteLay = (LinearLayout) inflater.inflate(R.layout.view_container, null);
        flowView = (FlowLayout)spriteLay.findViewById(R.id.flowView);
        add_curapp = (TextView)spriteLay.findViewById(R.id.add_curapp);
        back = (TextView)spriteLay.findViewById(R.id.back);
        del = (TextView)spriteLay.findViewById(R.id.del);
        add = (TextView)spriteLay.findViewById(R.id.add);
        add_curapp.setOnClickListener(this);
        back.setOnClickListener(this);
        del.setOnClickListener(this);
        add.setOnClickListener(this);
        
        dm = getResources().getDisplayMetrics();
    }
    
    public static FloatView createView() {
        wmParams = new WindowManager.LayoutParams();  
        //获取的是WindowManagerImpl.CompatModeWrapper  
        mWindowManager = (WindowManager)MyApplication.getContext().getSystemService(Context.WINDOW_SERVICE);  
        //设置window type  
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        //设置图片格式，效果为背景透明  
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）  
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;        
        //调整悬浮窗显示的停靠位置为左侧置顶  
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        // 以屏幕左上角为原点，设置x、y初始值，相对于gravity  
        wmParams.x = 0;  
        wmParams.y = 200;  
        //设置悬浮窗口长宽数据    
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;  
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;  
     
        inflater = LayoutInflater.from(MyApplication.getContext());
        //获取浮动窗口视图所在布局  
        FloatView floatView = (FloatView) inflater.inflate(R.layout.view_float, null);
        floatView.measure(View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        //添加mFloatLayout  
        mWindowManager.addView(floatView, wmParams);
        return floatView;
    }

    public void showFloatView() {
         mWindowManager.addView(this, wmParams);  
    }
    
    public void hideFloatView() {
        mWindowManager.removeView(this);
    }
    
    private void onClickSpirt(){
        if(!isOpenFloat) {
            removeView(mFloatView);
            addView(spriteLay, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            isOpenFloat = true;
        }else {
            closeFloat();
        }
    }
    
    public void closeFloat() {
        if(isOpenFloat) {
            removeView(spriteLay);
            addView(mFloatView);
            isOpenFloat = false;
            isEditable = false;
            changeEditView();
        }
    }
    
    public void addSpirteView(Spriter one) {
        flowView.addView(one.getView(inflater, one, isEditable));
    }
    
    public void rmvSpirteView(Spriter one) {
        View child = flowView.findViewWithTag(one.uri);
        if(child != null) {
            flowView.removeView(child);
        }
    }
    
    private void changeEditView() {
        int size = flowView.getChildCount();
        for(int i =0; i < size; i++) {
            SpirteView child = (SpirteView)flowView.getChildAt(i);
            child.setEditable(isEditable);
        }
    }
    
    private void hideLeft() {
        LayoutParams lp = (LayoutParams)mFloatView.getLayoutParams();
        lp.leftMargin = (int)(-20*dm.density);
        lp.rightMargin = 0;
        lp.bottomMargin = 0;
        isHide = true;
        wmParams.x = 0;
        mWindowManager.updateViewLayout(this, wmParams);       
    }
    
    private void hideRight() {
        LayoutParams lp = (LayoutParams)mFloatView.getLayoutParams();
        lp.rightMargin = (int)(-20*dm.density);
        lp.leftMargin = 0;
        lp.bottomMargin = 0;
        isHide = true;
        wmParams.x = dm.widthPixels - mFloatView.getMeasuredWidth()/2;
        mWindowManager.updateViewLayout(this, wmParams);
    }
    
    private void hideBottom() {
        LayoutParams lp = (LayoutParams)mFloatView.getLayoutParams();
        lp.bottomMargin = (int)(-30*dm.density);
        lp.leftMargin = 0;
        lp.rightMargin = 0;
        isHide = true;
        wmParams.y = dm.heightPixels - mFloatView.getMeasuredHeight()/2;
        mWindowManager.updateViewLayout(this, wmParams);
    }
    
    private void restoreFloat() {
        LayoutParams lp = (LayoutParams)mFloatView.getLayoutParams();
        lp.bottomMargin = 0;
        lp.rightMargin = 0;
        lp.leftMargin = 0;
        mWindowManager.updateViewLayout(this, wmParams);
    }
  
    @Override
    public void onClick(View v) {
        switch(v.getId()) {
        case R.id.add_curapp:{
            addCurApp();
            break;
        }
        case R.id.back:{
            onClickSpirt();
            break;
        }
        case R.id.del:
        {
            isEditable = !isEditable;
            changeEditView();
            break;
        }
        case R.id.add:{
            MainActivity.startActivity(getContext());
            break;
        }
        }
    }
    
    private int lastX = 0;
    private int lastY = 0;
    @Override  
    public boolean onTouch(View v, MotionEvent event)   
    {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            if(isHide) {
                restoreFloat();
            }
        }else
        if(event.getAction() == MotionEvent.ACTION_UP) {
            if(!isMoving) {
                onClickSpirt();
            }else {
                isMoving = false;
                if(!isOpenFloat) {
                    if(wmParams.x < mFloatView.getMeasuredWidth()/3) {
                        hideLeft();
                    }else 
                    if(wmParams.x > dm.widthPixels - mFloatView.getMeasuredWidth()*4/3){                       
                        hideRight();
                    }else
                    if(wmParams.y > dm.heightPixels - mFloatView.getMeasuredHeight()*4/3){
                        hideBottom();
                    }else {
                        isHide = false;
                    }
                }
            }
        }else
        if(event.getAction() == MotionEvent.ACTION_MOVE)
        {
            //getRawX是触摸位置相对于屏幕的坐标，getX是相对于按钮的坐标
            wmParams.x +=( (int) event.getRawX() - lastX);
            //减25为状态栏的高度
            wmParams.y += ((int) event.getRawY() - lastY);
            //刷新
            mWindowManager.updateViewLayout(this, wmParams);
            isMoving = true;
        }else
        if(event.getAction() == MotionEvent.ACTION_CANCEL) {
            if(isMoving) {
                isHide = false;
            }
        }
        lastX = (int)event.getRawX();
        lastY = (int)event.getRawY();
        //此处必须返回false，否则OnClickListener获取不到监听
        return true;
    }
    
    private void addCurApp() {
        ActivityManager am = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE); 
        List<RunningTaskInfo> cn = am.getRunningTasks(1); 
        RunningTaskInfo taskInfo=cn.get(0); 
        ComponentName name=taskInfo.topActivity; 
        String pkg = name.getPackageName();
        try {
            PackageManager pm = getContext().getPackageManager();
            ApplicationInfo appInfo = getContext().getPackageManager().getApplicationInfo(pkg, PackageManager.GET_META_DATA);
            String appName = appInfo.loadLabel(pm).toString();
            SpriterManager.getInstance(getContext()).add(new Spriter(SpriterType.APP, appName, pkg));
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }
}